//
//  BRPageContro.swift
//  FrameMain
//
//  Created by Burn on 2019/1/15.
//  Copyright © 2019 nmgxysh. All rights reserved.
//

import UIKit

enum Location {
    case LocationCenter
    case LocationLeft
    case LocationRight
}

fileprivate let pageW : CGFloat = 8
fileprivate let pageSpacing : CGFloat = 3

class BRPageControl: UIView {
    //  未选中状态
    var pageIndicatorTintColor : UIColor = UIColor.lightGray
    //   选中状态
    var currentPageIndicatorTintColor : UIColor = UIColor.orange
    //  只有一个页面隐藏
    var hidesForSinglePage : Bool = true
    //  多少个
    var _numberOfPages : Int = 0
    var numberOfPages : Int{
        set{
            _numberOfPages = newValue
            addSubViews()
        }get{
            return _numberOfPages;
        }
    }
    //  当前下表
    var _currentPage : Int = 0
    var currentPage : Int{
        set{
            _currentPage = newValue
            setCurrent()
        }get{
            return _currentPage
        }
    }
    //  上次选中的Page
    var lastTimePage : UILabel?
    //  对齐
    var location : Location = .LocationCenter
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //  添加
//        addSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


extension BRPageControl {
    fileprivate func addSubViews(){
        var x : CGFloat = 0.0
        switch location {
        case .LocationCenter:
            let w = _numberOfPages * Int(pageW) + (_numberOfPages - 1) * Int(pageSpacing)
            x = frame.size.width * 0.5 - CGFloat(w / 2)
        case .LocationLeft:
            x = 10
        case .LocationRight:
            let w = _numberOfPages * Int(pageW) + (_numberOfPages - 1) * Int(pageSpacing)
            x = frame.size.width - CGFloat(w) - 10.0
        }
        
        for i in 0..<_numberOfPages {
            let page = UILabel(frame: CGRect(x: x + CGFloat(i) * pageW + CGFloat(i) * pageSpacing, y: 0, width: pageW, height: 2))
            page.tag = 1000 + i
            page.backgroundColor = pageIndicatorTintColor
            addSubview(page)
        }
    }
    
    fileprivate func setCurrent(){
        print(_currentPage);
        
        if lastTimePage != nil {
            lastTimePage?.backgroundColor = pageIndicatorTintColor
        }
        
        let currentPage = self.viewWithTag(1000 + _currentPage)
        guard let currentPageG = currentPage else { return }
        currentPageG.backgroundColor = currentPageIndicatorTintColor
        
        lastTimePage = currentPage as! UILabel
    }
}
